const passageDictionary = (function () {
  /** @type {Map<string, PassageDictionary>}*/
  const anchorDictMap = new Map();
  /**
   * @typedef {{
   *  title: string,
   *  $container: HTMLElement,
   *  parent: PassageDictionary | null,
   *  contents: PassageDictionary[],
   * }} PassageDictionary
   *  @type {PassageDictionary}
   */
  const dictionaryRoot = { contents: [], }

  const openedNameSet = new Set();

  function initDictElement(name) {
    const $el = document.createElement('div');
    $el.className = 'dict-container'
    $el.innerHTML = `
      <a class="dict-title">${name.replace(/-/g, " ")}</a>
      <div class="dict-content"></div>`
    return $el
  }


  let $container = null;

  function appendDictElement($child, $parent) {
    if ($parent === null) {
      $container.appendChild($child);
      return;
    }
    $parent.querySelector('.dict-content').appendChild($child);
  }


  function openSingle(title) {
    removeClassName(anchorDictMap.get(title).$container.querySelector('.dict-content'), 'hidden');
    openedNameSet.add(title);
  }

  function closeSingle(title) {
    addClassName(anchorDictMap.get(title).$container.querySelector('.dict-content'), 'hidden');
    openedNameSet.delete(title);
  }

  function openToTop(title) {
    const dict = anchorDictMap.get(title);
    openSingle(title)
    if (dict.parent !== dictionaryRoot) {
      openToTop(dict.parent.title);
    }
  }

  function closeAll() {
    openedNameSet.forEach((title) => closeSingle(title));
  }

  let lastReading = null
  function currentReading(title) {
    if (lastReading === title) {
      return;
    }
    addClassName(anchorDictMap.get(title).$container, "current")
    if (lastReading !== null)
      removeClassName(anchorDictMap.get(lastReading).$container, "current")
    lastReading = title;
  }

  /**
   * 从文章内容中生成目录
   * @param {HTMLElement} $parent 目录容器
   * @param {HTMLElement} $content 文章
   */
  function initFromContent($parent, $content) {
    let dictLevelArr = [dictionaryRoot],
      lastDictLevel = 0;
    const $chilren = $content.children;
    $container = $parent
    for (let index = 0; index < $chilren.length; index++) {

      const $child = $chilren[index];
      if (!/H[1-6]/.test($child.tagName)) continue; // 如果不是标题，就跳过
      const curDictLevel = +$child.tagName[1];
      const name = $child.querySelector('a').getAttribute('name');
      const $container = initDictElement(name);

      // console.log(lastDictLevel, curDictLevel, name, dictLevelArr)
      const curDictionary = {
        title: name,
        $container: $container,
        parent: dictLevelArr[curDictLevel - 1],
        contents: []
      }
      dictLevelArr[curDictLevel] = curDictionary;
      dictLevelArr[curDictLevel - 1].contents.push(curDictionary);

      if (curDictLevel === 1) {
        appendDictElement($container, null)
      } else {
        appendDictElement($container, curDictionary.parent.$container)
      }

      anchorDictMap.set(name, curDictionary)

      $container
        .querySelector('.dict-title')
        .setAttribute('href', `javascript:undefined`)

      $container
        .querySelector('.dict-title').addEventListener('click', function () {
          mdIFrame.scrollToAnchor(name);
          setTimeout(() => {
            closeAll();
            openToTop(name);
            currentReading(name)
          }, 0);
        })

      $container.addEventListener('click', function () {
        openSingle(name)
      })

      openedNameSet.add(name)

      lastDictLevel = curDictLevel
    }

    mdIFrame.watchScroll(($anchor) => {
      closeAll();
      openToTop($anchor.getAttribute('name'))
      currentReading($anchor.getAttribute('name'))
    })

    closeAll()
  }

  return initFromContent
})();



const passageDictionaryFixed = (function () {
  const $dict = document.getElementById('passage-dict');
  const initOffsetTop = $dict.offsetTop
  const fixedTop = 10;
  function animation() {
    const curScrollTop = document.documentElement.scrollTop;
    if (curScrollTop > initOffsetTop + fixedTop) {
      $dict.style.position = `fixed`
      $dict.style.top = fixedTop + 'px'
    } else {
      $dict.style.position = ''
      $dict.style.top = fixedTop + ''
    }
  }

  document.addEventListener('scroll', animation)

  return animation
})()

